
<template>
  <check-account>
    <template #form="{id}">
      <div class="action-card-container app-dialog www" :data-id="setID(id)">
        <el-form class="form-content"
          ref="staff-form" label-position="left"
          :model="baseData" label-width="140px">
          <div class="form-title">绑定银行卡</div>
          <el-form-item class="form-content-item"
              label="账户名称：" prop="acctnoName"
              :rules="{ required: true, message: `账户名称不能为空`, trigger: 'blur'}">
              <div class="form-val flex-normal">
                <el-input v-model="baseData['acctnoName']" placeholder="请输入账户名称"></el-input>
              </div>
          </el-form-item>
          <el-form-item class="form-content-item"
              label="银行账号：" prop="linkedAcctno"
              :rules="{ required: true, message: `银行账号不能为空`, trigger: 'blur'}">
              <div class="form-val flex-normal">
                <el-input v-model="baseData['linkedAcctno']" placeholder="请输入银行账号"></el-input>
              </div>
          </el-form-item>
          <el-form-item class="form-content-item" prop="bankCode"
              label="开户行：" :rules="{ required: true, message: `开户行不能为空`, trigger: 'change'}">
              <div class="form-val flex-normal">                
                <el-select v-model="baseData['bankCode']" 
                placeholder="请选择" filterable  @change="bankChange">
                  <el-option v-for="(i, idx) in bankList" :key="idx" :label="i.bankName"
                    :value="i.bankCode"></el-option>
                </el-select>
              </div>
          </el-form-item>
          <el-form-item class="form-content-item"
              label="开户地区：" prop="cityCode"
              :rules="{ required: true, message: `开户地区不能为空`, trigger: 'change'}">
              <div class="form-val flex-normal">
                <el-cascader filterable :props="{
                  value: 'code', label: 'region', children: 'cities'
                }"  @change="areaChange"
                v-model="baseData['cityCode']" placeholder="请选择" 
                :options="cityList"></el-cascader>
              </div>
          </el-form-item>
          <el-form-item class="form-content-item"
            label="所属支行：" prop="cnapsCode"
            :rules="{ required: true, message: `所属支行不能为空`, trigger: 'change'}">
            <div class="form-val flex-normal">
              <el-select v-model="baseData['cnapsCode']" 
                placeholder="请选择" filterable>
                <el-option v-for="(i, idx) in zhList" :key="idx" :label="i.brabank_name"
                  :value="i.cnaps_code"></el-option>
              </el-select>
            </div>
          </el-form-item>
        </el-form>
        <div class="btn-container flex-normal">
          <div class="btn-item reset flex-center">
            <span class="btn-txt">重置信息</span>
          </div>
          <el-button :loading="boo.isSubmit" type="primary" class="btn-item submit flex-center" @click="submit('staff-form')">
            <span class="btn-txt">提交开户</span>
          </el-button>
        </div>
      </div> 
      <dialog-normal
        ref="dialog-pwd"
        :dialog-prop="{
            title: '支付密码设置',
            height: '400px',
            width: '800px',
            submit: '提交'
        }" @normal-submit="submitDialog">
        <template #dialog-content>
          <div class="check-warning flex-normal">
            <i class="desc-icon el-icon-info"></i>
            <span class="desc-txt">密码仅支持数字及字母组合，不支持标点符号</span>
          </div>
          <div class="LPay-code-container">
            <div class="flex-normal">
              <span class="Lpay-label">支付密码：</span>
              <div id="ipt_pwd2" class="flex-normal ipt-pwd-content">
                <span id="LOGPASS2_SHOW" class="placehoder-txt">请输入密码</span>
                <input id="LOGPASS2" class="default input_search" type="password" disabled="disabled" />
                <div id="keyboardBtn2" class="ipt_pwd_rjp default"></div>
              </div>
            </div>
            <div class="flex-normal">
              <span class="Lpay-label">确认密码：</span>
              <div id="ipt_pwd3" class="flex-normal ipt-pwd-content">
                <span id="LOGPASS3_SHOW" class="placehoder-txt">请确认密码</span>
                <input id="LOGPASS3" class="default input_search" type="password" disabled="disabled" />
                <div id="keyboardBtn3" class="ipt_pwd_rjp default"></div>
              </div>
            </div>
          </div>
        </template>
      </dialog-normal>
    </template>
  </check-account>
</template>

<script>
import {LLKeyBord} from '@/utils/tools.js'
import {
  submitShopOpenAccount, getRandom, shopOpenVerify,
  getBankCode, getCityList, getCnapsCode
} from "@/api/financeManage/lpay.js";
export default {
  components: {
    "check-account": () => import("../temp/check-account.vue"),
    "dialog-normal": () => import("@/rhComponents/dialog/normal-dialog"),
  },
  data() {
    return {
      id: '',
      other: {
        brabank_name: '',
        city_code: '',
        bank_code: '',
      },
      boo: {
        loading: true,
        isSubmit: false
      },
      baseData: {},
      LPayProp: {
        options: {},
        status: '',
        passwordInstance: null,
        passwordHashInstance: null,
        params: {},
        pwdError: false,
      },
      timerObj: {
        timer: null,
        seconds: 60,
        loading: false,
        tips: '获取验证码'
      },
      bankList: [], //银行列表
      cityList: [], //城市列表
      zhList: [], //支行列表
    };
  },
  watch: {

  },
  mounted(){
    let _self = this
    _self.getBankList()
    _self.getCityList()
  },
  methods: {
    setID(id){
      this.id = id
    },
    async getBankList(){
      let _self = this
      await getBankCode().then(res => {
        _self.bankList = res.data
      })
    },
    async getCityList(){
      let _self = this
      await getCityList().then(res => {
        _self.cityList = res.data
      })
    },
    bankChange(val){
      let _self = this
      _self.other.bank_code = val
      let bank = _self.bankList.find(i => i.bankCode == val)
      _self.other.brabank_name = bank.bankName
      _self.getZhList()
    },
    areaChange(val){
      let _self = this
      _self.other.city_code = val[1]
      _self.getZhList()
    },
    async getZhList(){
      let _self = this
      let {bank_code, city_code} = _self.other
      _self.$set(_self.baseData, 'cnapsCode', '')
      _self.zhList = []
      if(!bank_code || bank_code == '') return
      if(!city_code || city_code == '') return
      await getCnapsCode(_self.other).then(res => {
        _self.zhList = res.data
      })
    },
    getRandom(){
      let _self = this
      getRandom().then(res => {
        _self.LPayProp.options = res.data
      })
    },
    initPassword() {
      let _self = this
      let paramsPwd = {
        click_objId: '#keyboardBtn2', 
        Input_texId: '#LOGPASS2',
        parent_objId: '#ipt_pwd2',
        placeholderId: '#LOGPASS2_SHOW'
      }
      const passowrd = LLKeyBord(paramsPwd, _self.LPayProp.options, (res) => {
        _self.LPayProp.pwdError = false
      }, (err) => {
        _self.LPayProp.pwdError = true
        _self.$message.error('密码格式错误')
      })
      
      let paramsPwdHash = {
        click_objId: '#keyboardBtn3', 
        Input_texId: '#LOGPASS3',
        parent_objId: '#ipt_pwd3',
        placeholderId: '#LOGPASS3_SHOW'
      }
      const passowrdHash = LLKeyBord(paramsPwdHash, _self.LPayProp.options, (res) => {
        _self.LPayProp.pwdError = false
      }, (err) => {
        _self.LPayProp.pwdError = true
        _self.$message.error('密码格式错误')
      })
      passowrd.initOptions()
      passowrdHash.initOptions()
      _self.LPayProp.passwordInstance = passowrd
      _self.LPayProp.passwordHashInstance = passowrdHash
    },
    async getSmsCode(){
      let _self = this, isSuccess = false
      let params = JSON.parse(JSON.stringify(_self.baseData))
      params.cityCode = _self.baseData['cityCode'][1] || ''
      await submitShopOpenAccount({id: _self.id, ...params}).then(res => {
        let {txn_seqno, token} = res.data
        // _self.$set(_self.LPayProp.params, 'txn_seqno', txn_seqno)
        // _self.$set(_self.LPayProp.params, 'token', token)        
        isSuccess = true
      })
      return isSuccess
    },
    submit(ref) {
      let _self = this;
      this.$refs[ref].validate(async (valid) => {
        if (valid) {
          _self.boo.isSubmit = true
          _self.getRandom()
          let isSuccess = await _self.getSmsCode().finally(() => {
            _self.boo.isSubmit = false
          })
          if(isSuccess){
            _self.$refs[`dialog-pwd`].showDialog = true
            _self.$nextTick(() => {
              _self.initPassword()
            })
          }
        } else {
          return false;
        }
      });
    },
    async submitDialog(){
      let _self = this
      let {passwordInstance, passwordHashInstance, pwdError} = _self.LPayProp
      if(pwdError){
        vm.loading = false
        return _self.$message.error('密码格式错误')
      }
      let vm = _self.$refs['dialog-pwd']
      // 获取国密密文
      passwordInstance.setRandKey(_self.LPayProp.options.random_value) // 先设置随机key
      const password = passwordInstance.getOutputSM() // 国密加密密码
      const rsaPassword = passwordInstance.getOutput() // RSA加密密码
      // hash用于比对密码是否一致，同一个密码加密密文可能不同，hash一定相同
      const hash = passwordInstance.getHash() // RSA加密密码
      const hash2 = passwordHashInstance.getHash() // RSA加密密码
      if(!hash || hash == '') {
        vm.loading = false
        return _self.$message.error('密码不能为空')
      }
      if(hash != hash2) {
        vm.loading = false
        return _self.$message.error('密码输入不一致')
      }
      let params = {
        // txn_seqno: _self.LPayProp.params['txn_seqno'],
        id: _self.id,
        password: password,
        random_key: _self.LPayProp.options['random_key'],
      }
      // return vm.loading = false
      await shopOpenVerify(params).then(res => {
        vm.showDialog = false        
        _self.$message.success('验证成功，3s后返回账户中心')
        setTimeout(() => {
          _self.$router.replace({name: 'FinanceStore'})
        }, 3500)
      }).catch(err => {
        _self.getRandom()
      }).finally(() => {
        vm.loading = false
      })
    },
  }
};
</script>
<style scoped lang="scss">
.www{
  padding: 0 vw(30);
  .form-content-item {
    position: relative;
    .form-txt{
      font-size: 13px;
    }
  }
  .form-title{
    margin-top: vh(30);
    margin-bottom: vh(20);
    line-height: vh(34);
    font-size: vh(16);
    color: #0003AA;
  }
  .form-val {
    width: vw(360);
    flex-wrap: nowrap;
    &.no-border{
      border: none;
    }
  }
}
.btn-container{
  padding-left: vw(30);
  margin-top: vh(80);
  .btn-item{
    height: vh(46);
    border-radius: vh(3);
    padding: 0 vw(60);
    margin-right: vw(30);
    &:last-child{
      margin-right: 0;
    }
    &.reset{
      .btn-txt{
        color: #0003AA;
        cursor: pointer;
      }
    }
    &.submit{
      cursor: pointer;
      background-color: #0003AA;
      .btn-txt{
        color: #fff;
      }
    }
    .btn-txt{
      font-size: vh(16);
    }
  }
}
.dialog-warning{
  align-items: center;
  margin-top: vh(80);
  .icon{
    width: vh(95);
    height: vh(95);
  }
  .warning-txt{
    color: #3D3D3D;
    font-size: 13px;
    margin-top: vh(30);
  }
}
.LPay-code-container ::v-deep{
  .el-input__inner{
    border: none;
  }
  .code-btn-unit{
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
    cursor: pointer;
    background: rgba(0, 3, 170, 0.1);
    border-radius: vh(3);
    height: vh(36);
    padding: 0 vw(15);
    .btn-txt{
      font-size: 13px;
      color: #0003AA;
    }
  }
  .ipt-pwd-content{
    height: 60px;
    position: relative;
    width: 60%;
    border-bottom: 1px solid #D8D8D8;
    margin-bottom: 10px;
    .placehoder-txt{
      color: #999;
      font-size: 13px;
    }
  }
  .Lpay-label{
    font-size: 13px;
    width: 120px;
  }
}
.check-warning{
  padding-left: vw(20);
  .desc-icon{
    color: #F7B212;
  }
  .desc-txt{
    margin-left: vw(10);
    font-size: vh(12);
    color: #7F7F7F;
  }
}
</style>